package com.codejiwei.akka;

import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;

// Worker Actor
class WorkerActor extends AbstractActor {
    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .matchAny(message -> {
                    if (message instanceof Integer) {
                        int number = (Integer) message;
                        int result = number * 2; // 处理工作
                        getSender().tell(result, getSelf()); // 将结果发送给发送者
                    }
                })
                .build();
    }
}

// Master Actor
class MasterActor extends AbstractActor {
    private final ActorRef workerActor;

    public MasterActor() {
        this.workerActor = getContext().actorOf(Props.create(WorkerActor.class), "workerActor");
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .matchAny(message -> {
                    if (message instanceof Integer) {
                        int number = (Integer) message;
                        workerActor.tell(number, getSelf()); // 将请求发送给 WorkerActor
                    } else if (message instanceof Integer) {
                        System.out.println("Result: " + message); // 处理 WorkerActor 返回的结果
                    }
                })
                .build();
    }
}

public class AkkaActorExample {
    public static void main(String[] args) {
        // 创建 Actor 系统
        ActorSystem system = ActorSystem.create("akka-system");

        // 创建 MasterActor
        ActorRef masterActor = system.actorOf(Props.create(MasterActor.class), "masterActor");

        // 发送消息给 MasterActor
        masterActor.tell(5, ActorRef.noSender());

        // 关闭 Actor 系统
        system.terminate();
    }
}
